package com.treasure.hunt.wxapi

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import com.blankj.utilcode.util.LogUtils
import com.module.lemlin.util.iwxapi
import com.tencent.mm.opensdk.constants.ConstantsAPI
import com.tencent.mm.opensdk.modelbase.BaseReq
import com.tencent.mm.opensdk.modelbase.BaseResp
import com.tencent.mm.opensdk.modelmsg.SendAuth
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler
import com.treasure.hunt.entity.Action
import com.treasure.hunt.entity.AuthResult
import com.treasure.hunt.entity.MainBean
import org.greenrobot.eventbus.EventBus

class WXEntryActivity : Activity(), IWXAPIEventHandler {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        iwxapi.handleIntent(intent, this)
    }

    override fun onResp(p0: BaseResp?) {
        finish()
        when (p0?.type) {
            ConstantsAPI.COMMAND_SENDMESSAGE_TO_WX -> {
                //分享--分享不再告知是否成功
                val mainBean: MainBean<Action, Any> = MainBean(
                    type = Action.GO_SHARE
                )
                EventBus.getDefault().post(mainBean)
            }
            ConstantsAPI.COMMAND_SENDAUTH -> {
                //登录
                if (p0 !is SendAuth.Resp) {
                    return
                }
                val authResult: AuthResult = when (p0.errCode) {
                    BaseResp.ErrCode.ERR_OK -> AuthResult.SUCCESS
                    BaseResp.ErrCode.ERR_USER_CANCEL -> AuthResult.CANCEL
                    else -> AuthResult.FAILURE
                }
                val mainBean: MainBean<AuthResult, String> = MainBean(
                    type = authResult,
                    data = if (authResult == AuthResult.SUCCESS) p0.code else null
                )
                EventBus.getDefault().post(mainBean)
            }
        }
    }

    override fun onReq(p0: BaseReq?) {

    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        setIntent(intent)
        iwxapi.handleIntent(intent, this)
    }
}